package logic

import (
	"context"
	"errors"
	"goods/cache"
	"goods/models/mysql"
	"goods/pkg"

	"goods/goodsrpc/goodsrpc"
	"goods/goodsrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *goodsrpc.UpdatePasswordRequest) (*goodsrpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Mobile).Result()
	if result != in.SendSms {
		return nil, errors.New("短信验证码输入错误请重新输入")
	}
	var user mysql.User
	mysql.DB.Debug().Where("mobile=?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("用户不存在无法修改")
	}
	if in.Password != in.NewPassword {
		return nil, errors.New("两次密码输入不一致")
	}
	if user.Password == pkg.Md5Str(in.Password) {
		return nil, errors.New("新旧密码一致")
	}
	in.Password = user.Password

	return &goodsrpc.UpdatePasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
